package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// Venue 场地模型
type Venue struct {
	BaseModel
	Name             string  `orm:"size(100)" json:"name"`
	StoreId          int64   `orm:"index" json:"store_id"`                    // 所属门店ID
	Capacity         int     `orm:"default(0)" json:"capacity"`               // 容纳人数
	Area             float64 `orm:"digits(10);decimals(2)" json:"area"`       // 面积（平方米）
	HourPrice        float64 `orm:"digits(10);decimals(2)" json:"hour_price"` // 小时价格
	TimeBasedPricing string  `orm:"type(text)" json:"time_based_pricing"`     // 分时段定价，JSON格式存储
	DayPrice         float64 `orm:"digits(10);decimals(2)" json:"day_price"`  // 全天价格
	Description      string  `orm:"size(500)" json:"description"`
	SpecialNotice    string  `orm:"size(50)" json:"special_notice"` //特殊提示
	Facilities       string  `orm:"size(500)" json:"facilities"`    // 设施，JSON格式存储
	Images           string  `orm:"size(1000)" json:"images"`       // 场地图片，JSON格式存储
	Status           int8    `orm:"default(1)" json:"status"`       // 1:空闲中, 2:使用中, 3:保洁中, 4:待保洁, 5:维护中
	SortOrder        int     `orm:"default(0)" json:"sort_order"`   // 排序
	VenueType        string  `orm:"size(50)" json:"venue_type"`     // 场地类型
	OpeningHours     string  `orm:"size(500)" json:"opening_hours"` // 开放时间，JSON格式存储
}

// TableName 设置表名
func (v *Venue) TableName() string {
	return "ss_venue"
}

// GetVenueById 根据ID获取场馆信息
func GetVenueById(id int64) (*Venue, error) {
	venue := &Venue{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(venue)

	if err != nil {
		return nil, err
	}

	// 如果场馆已被删除，则返回错误
	if venue.IsDeleted == 1 {
		return nil, orm.ErrNoRows
	}

	return venue, nil
}

// GetVenueList 获取场地列表
func GetVenueList(page, pageSize int, filters map[string]interface{}) ([]*Venue, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Venue))

	// 应用过滤条件
	if storeId, ok := filters["store_id"].(int64); ok {
		qs = qs.Filter("store_id", storeId)
	}

	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	if minCapacity, ok := filters["min_capacity"].(int); ok {
		qs = qs.Filter("capacity__gte", minCapacity)
	}

	if maxCapacity, ok := filters["max_capacity"].(int); ok {
		qs = qs.Filter("capacity__lte", maxCapacity)
	}

	if venueType, ok := filters["venue_type"].(string); ok && venueType != "" {
		qs = qs.Filter("venue_type", venueType)
	}

	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var venues []*Venue
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&venues)

	return venues, total, err
}

// CreateVenue 创建场地
func CreateVenue(venue *Venue) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(venue)
	return id, err
}

// UpdateVenue 更新场地信息
func UpdateVenue(venue *Venue, fields ...string) error {
	o := orm.NewOrm()

	// 如果没有指定字段，则更新所有字段
	if len(fields) == 0 {
		_, err := o.Update(venue)
		return err
	}

	// 否则只更新指定字段
	_, err := o.Update(venue, fields...)
	return err
}

// DeleteVenue 删除场地（软删除）
func DeleteVenue(id int64) error {
	o := orm.NewOrm()
	venue := &Venue{BaseModel: BaseModel{Id: id}}
	if err := o.Read(venue); err != nil {
		return err
	}

	venue.IsDeleted = 1
	_, err := o.Update(venue, "IsDeleted")
	return err
}

// GetVenuesByStoreId 获取指定门店的场地列表
func GetVenuesByStoreId(storeId int64) ([]*Venue, error) {
	o := orm.NewOrm()
	var venues []*Venue
	_, err := o.QueryTable(new(Venue)).Filter("store_id", storeId).Filter("is_deleted", 0).OrderBy("sort_order", "-id").All(&venues)
	return venues, err
}

// GetVenueCount 获取场地总数
func GetVenueCount(franchiseId int64) (int64, error) {
	o := orm.NewOrm()
	var count int64

	// 构建查询条件
	whereClause := "is_deleted = 0"
	params := []interface{}{}

	// 如果是加盟商，添加加盟商过滤条件
	if franchiseId > 0 {
		whereClause += " AND franchise_id = ?"
		params = append(params, franchiseId)
	}

	// 执行查询
	err := o.Raw("SELECT COUNT(*) FROM ss_venue WHERE "+whereClause, params...).QueryRow(&count)
	return count, err
}

// GetVenuesByIds 根据ID列表获取场馆信息
func GetVenuesByIds(ids []int64) ([]*Venue, error) {
	o := orm.NewOrm()
	var venues []*Venue
	_, err := o.QueryTable(new(Venue)).Filter("id__in", ids).Filter("is_deleted", 0).All(&venues)
	return venues, err
}

// BatchUpdateVenueStatus 批量更新场地状态
func BatchUpdateVenueStatus(venueIDs []int64, status int8) (int64, error) {
	if len(venueIDs) == 0 {
		return 0, nil
	}
	o := orm.NewOrm()
	num, err := o.QueryTable(new(Venue)).Filter("id__in", venueIDs).Update(orm.Params{
		"status": status,
	})
	return num, err
}
